package cn.snmp.mutual.common.tools;

import lombok.extern.slf4j.Slf4j;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @since 2018.9.16
 * @author dengkn
 * StackPrinter
 */
@Slf4j
public class StackPrinter {
    private BufferedWriter bufferedWriter;

    public StackPrinter(String typeName) {
        this(typeName,  null);
    }

    public StackPrinter(String typeName, String dataFormat) {
        if (typeName == null || typeName.length() == 0) {
            typeName = "Default";
        }

        if (dataFormat == null || dataFormat.length() == 0) {
            dataFormat = "yyyyMMddHHmmss";
        }

        String name = "data_collect" + File.separator + typeName + (new SimpleDateFormat(dataFormat)).format(new Date())
                + ".log";
        this.initIO(name);
    }

    private void initIO(String fileName) {
        File dir = new File("data_collect");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error("initIO error e= " + e);
                return;

            }
        }

        try {
            this.bufferedWriter = new BufferedWriter(new FileWriter(file, true));
        } catch (IOException arg4) {
            this.close();
        }

    }

    public void close() {
        try {
            if (this.bufferedWriter != null) {
                this.bufferedWriter.close();
            }
        } catch (IOException arg1) {

        }

    }

    public synchronized void print(String str) {
        if (this.bufferedWriter != null) {
            try {
                this.bufferedWriter.append("DataCollect: ");
                this.bufferedWriter.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
                this.bufferedWriter.newLine();
                this.bufferedWriter.append(str);
                this.bufferedWriter.newLine();
                StackTraceElement[] e = Thread.currentThread().getStackTrace();
                int i = 3;
                for (int length = e.length; i < length; ++i) {
                    this.bufferedWriter.append(e[i].toString());
                    this.bufferedWriter.newLine();
                }
                this.bufferedWriter.flush();
            } catch (IOException e) {
                log.error("print error " + e);
            }

        }
    }
}